from flask import Flask, render_template, request, jsonify, session
from config import Config
from simple_maas_client import EnglishAITutor
import json

app = Flask(__name__)
app.secret_key = Config.SECRET_KEY

# 初始化 tutor
try:
    tutor = EnglishAITutor()
    print("✅ AI导师初始化成功")
    
    # 测试连接
    test_result = tutor.test_connection()
    if "抱歉" in test_result or "错误" in test_result:
        print(f"❌ 连接测试失败: {test_result}")
    else:
        print(f"✅ 连接测试成功: {test_result}")
    
except Exception as e:
    print(f"❌ AI导师初始化失败: {e}")
    exit(1)

@app.route('/')
def index():
    """首页"""
    return render_template('index.html')

@app.route('/chat', methods=['GET', 'POST'])
def chat():
    """智能聊天学习"""
    if request.method == 'POST':
        user_message = request.json.get('message')
        
        # 确保会话存在
        if 'conversation_history' not in session:
            session['conversation_history'] = []
        
        conversation_history = session['conversation_history']
        
        # 构建对话历史 - 使用英文系统提示词
        messages = [
            {"role": "system", "content": """You are a patient and professional English teacher. Please:
1. Communicate primarily in English
2. Correct grammar errors gently
3. Provide helpful explanations
4. Adjust to the student's level
5. Encourage practice and learning"""}
        ]
        
        # 添加历史对话（限制历史长度）
        for msg in conversation_history[-4:]:  # 保持最近4轮对话
            messages.append(msg)
        
        # 添加当前消息
        messages.append({"role": "user", "content": user_message})
        
        # 获取AI回复
        ai_response = tutor.chat(messages)
        
        # 更新对话历史（限制总长度）
        conversation_history.append({"role": "user", "content": user_message})
        conversation_history.append({"role": "assistant", "content": ai_response})
        
        # 限制对话历史长度（最多10条消息）
        if len(conversation_history) > 10:
            conversation_history = conversation_history[-10:]
        
        session['conversation_history'] = conversation_history
        
        return jsonify({"response": ai_response})
    
    return render_template('chat.html')

@app.route('/clear_chat', methods=['POST'])
def clear_chat():
    """清空对话历史"""
    session.pop('conversation_history', None)
    return jsonify({"success": True, "message": "对话历史已清空"})

@app.route('/grammar', methods=['GET', 'POST'])
def grammar_correction():
    """语法纠错"""
    if request.method == 'POST':
        text = request.json.get('text')
        if not text:
            return jsonify({"error": "Please enter text to check"})
        
        corrected = tutor.correct_grammar(text)
        return jsonify({"corrected": corrected})
    
    return render_template('grammar.html')

@app.route('/vocabulary', methods=['GET', 'POST'])
def vocabulary_learning():
    """词汇学习"""
    if request.method == 'POST':
        word = request.json.get('word')
        if not word:
            return jsonify({"error": "Please enter a word to search"})
        
        explanation = tutor.explain_vocabulary(word)
        return jsonify({"explanation": explanation})
    
    return render_template('vocabulary.html')

@app.route('/conversation', methods=['GET', 'POST'])
def conversation_practice():
    """情景对话练习"""
    if request.method == 'POST':
        scenario = request.json.get('scenario', 'daily')
        user_input = request.json.get('message', '')
        
        # 确保会话存在
        session_key = f'conversation_{scenario}'
        if session_key not in session:
            session[session_key] = []
        
        conversation_history = session[session_key]
        
        if user_input:
            # 继续对话
            messages = [
                {"role": "system", "content": f"You are in a {scenario} scenario. Have a natural English conversation with the student."}
            ]
            
            for msg in conversation_history:
                messages.append(msg)
            
            messages.append({"role": "user", "content": user_input})
            
            response = tutor.chat(messages, temperature=0.9)
            
            # 更新对话历史（限制长度）
            conversation_history.append({"role": "user", "content": user_input})
            conversation_history.append({"role": "assistant", "content": response})
            
            if len(conversation_history) > 8:
                conversation_history = conversation_history[-8:]
            
            session[session_key] = conversation_history
            
            return jsonify({"response": response})
        else:
            # 开始新对话
            session[session_key] = []
            initial_prompt = f"Let's practice English conversation in a {scenario} scenario. Please start the conversation."
            return jsonify({"response": initial_prompt})
    
    return render_template('conversation.html')

@app.route('/clear_conversation/<scenario>', methods=['POST'])
def clear_conversation(scenario):
    """清空特定场景的对话历史"""
    session_key = f'conversation_{scenario}'
    session.pop(session_key, None)
    return jsonify({"success": True, "message": f"{scenario} 场景对话历史已清空"})

if __name__ == '__main__':
    Config.validate()
    print(f"🔑 SECRET_KEY: {Config.SECRET_KEY[:16]}...")
    app.run(debug=True, host='0.0.0.0', port=5000)